<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\model\Admin;
use app\model\AuthRule;
use think\exception\ValidateException;
use app\validate\Login as ValidateLogin;
use think\Request;

class Login extends BaseController
{

    public function doLogin()
    {
        $mobile = $this->request->post('mobile');
        $password = $this->request->post('password');
        try {
            $this->validate(['mobile' => $mobile, 'password' => $password], ValidateLogin::class);
            if (!$admin = Admin::where('mobile', $mobile)->find()) {
                return $this->response(403, '用户名不存在');
            }
            if (!password_verify($password, $admin->password)) {
                return $this->response(403, '密码错误');
            }
            $token = $this->token->createToken($admin->id);
            $admin->token = $token;
            $admin->login_status = 1; //登录
            $admin->save();

        } catch (ValidateException $exception) {
            // 验证失败 输出错误信息
            return $this->response(403, $exception->getError());
        }
        return $this->response($admin->toArray());
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/7/22
     * @Time: 16:01
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取admin管理员信息
     */
    public function adminShow()
    {
        $admin = Admin::find($this->request->uid);
        if (is_null($admin)) {
            return $this->response(404, '此用户不存在');
        }
        // 检查用户权限
        $role_ids = array_column($admin->roles()->select()->toArray(),
            'rules');//获取该用户所属角色rules
        $where = [];
        if (!in_array('*', $role_ids)) {
            //->where('is_open', AuthRule::OPEN_ONE)
            $where[] = array('id', 'in', implode(',', $role_ids));
        }
        $data = AuthRule::field('id,name')->where($where)->select()->toArray();

        $url = [];
        foreach ($data as $key => $v) {
            $url[] = $v['name'];
        }
        $user['url'] = implode(',', $url);
        $user['role'] = implode(',', $role_ids);
        return $this->response($user);
    }
}
